package tools;

import java.util.concurrent.*;

/**
 * Author: m4n1c.4ny0neSec
 * Date: 2022/2/8
 * Desc:
 * 线程池工具
 */
public class ThreadTool {
    public static ExecutorService executor;

    static{

        int corePoolSize = 10; //核心线程数
        int maxinumPoolSize = 200; //支持最大线程数
        long keepAliveTime = 60 * 60; //线程存活时间
        TimeUnit unit = TimeUnit.SECONDS; //时间单位
        ThreadFactory factory = Executors.defaultThreadFactory(); //线程池种类
        ThreadPoolExecutor.AbortPolicy abortPolicy = new ThreadPoolExecutor.AbortPolicy(); //拒绝策略为抛出异常

        executor = new ThreadPoolExecutor(corePoolSize,maxinumPoolSize,keepAliveTime,unit,new SynchronousQueue<>(),factory,abortPolicy);
    }

    /**
     * 执行方法
     * @param task 传入方法
     */
    public static void submit(Runnable task){
        executor.submit(task);
    }

    /**
     * 关闭线程池
     * 调用之后不允许继续往线程池内继续添加线程;
     * 线程池的状态变为 SHUTDOWN 状态;
     * 所有在调用 shutdown() 方法之前提交到 ExecutorSrvice 的任务都会执行;
     * 一旦所有线程结束执行当前任务，ExecutorService 才会真正关闭
     */
    public static void shutDown(){executor.shutdown();}

    /**
     * executor提供一个原生函数isTerminated()来判断线程池中的任务是否全部完成。全部完成返回true，否则返回false
     * @return
     */
    public static boolean isTerminated(){return executor.isTerminated();}
}
